import React, { useState } from 'react';
import { Space, Switch, Table, Button, Modal, Form, Input, Select } from 'antd'; // 导入 Ant Design 的组件
import { PlusOutlined } from '@ant-design/icons'; // 导入 Ant Design 的图标
import "../../styles/pages/table.css"; // 导入表格样式
import IconMap from '../../utils/IconMap'; // 导入图标映射对象

const { Item } = Form;
const { Option } = Select;

// 定义 MenuTable 组件，接收 menuData 和 setMenuData 作为 props
const MenuTable = ({ menuData, setMenuData }) => {
    // 状态管理
    const [expandedKeys, setExpandedKeys] = useState([]); // 展开的行的 key
    const [isModalVisible, setIsModalVisible] = useState(false); // 模态框是否可见
    const [isAddMode, setIsAddMode] = useState(false); // 是否是新增模式
    const [selectedRecord, setSelectedRecord] = useState(null); // 选中的记录
    const [dataSource, setDataSource] = useState(menuData); // 数据源

    // 生成表格数据
    const generateTableData = (data, parentKey = '') => {
        // 遍历菜单数据，转换为表格数据格式
        return data.map((item, index) => {
            const key = item.key || (parentKey ? `${parentKey}-${index}` : `${index}`);
            const children = item.children ? generateTableData(item.children, key) : null;
            const hasChildren = Array.isArray(item.children) && item.children.length > 0;
            return {
                key: key,
                title: item.title,
                path: item.path,
                icon: item.icon,
                isShow: item.isShow,
                children: children,
                hasChildren: hasChildren,
            };
        });
    };

    // 处理展开行
    const handleExpand = (expanded, record) => {
        // 更新展开行的状态
        const { key } = record;
        const newExpandedKeys = expanded
            ? [...expandedKeys, key]
            : expandedKeys.filter(k => k !== key);

        // 如果展开行的菜单项有父菜单，则同时展开父菜单项
        if (expanded && record.parentKey) {
            setExpandedKeys([...newExpandedKeys, record.parentKey]);
        } else {
            setExpandedKeys(newExpandedKeys);
        }
    };

    // 处理编辑操作
    const handleEdit = (record) => {
        setSelectedRecord(record); // 设置选中的记录
        setIsAddMode(false); // 设置为编辑模式
        setIsModalVisible(true); // 打开模态框
    };

    // 处理删除操作
    const handleDelete = (record) => {
        // 递归删除函数
        const recursiveDelete = (data, keyToDelete) => {
            return data.reduce((acc, item) => {
                if (item.key === keyToDelete) {
                    return acc;
                }
                const children = item.children ? recursiveDelete(item.children, keyToDelete) : null;
                return [...acc, { ...item, children: children }];
            }, []);
        };

        // 更新数据源和展开行的状态
        const updatedData = recursiveDelete(dataSource, record.key);
        setDataSource(updatedData);
        setMenuData(updatedData);
        setExpandedKeys(expandedKeys.filter(key => key !== record.key));
    };

    // 处理新增操作
    const handleAdd = () => {
        setSelectedRecord(null); // 清空选中的记录
        setIsAddMode(true); // 设置为新增模式
        setIsModalVisible(true); // 打开模态框
    };

    // 确认按钮处理函数
    const handleOk = () => {
        setIsModalVisible(false); // 关闭模态框
    };

    // 取消按钮处理函数
    const handleCancel = () => {
        setIsModalVisible(false); // 关闭模态框
    };

    // 表单提交处理函数
    const onFinish = (values) => {
        // 如果是新增模式
        if (isAddMode) {
            // 新增记录到 dataSource
            const newKey = `${dataSource.length + 1}-${new Date().getTime()}`; // 生成唯一的 key
            const newRecord = {
                key: newKey,
                title: values.name,
                path: values.path,
                icon: values.icon,
                isShow: values.isShow,
                children: null,
            };

            // 递归添加记录到父菜单项
            const addRecordToParent = (data, parentKey) => {
                return data.map(item => {
                    if (item.key === parentKey) {
                        return {
                            ...item,
                            children: [...(item.children || []), newRecord],
                        };
                    }
                    if (item.children) {
                        return {
                            ...item,
                            children: addRecordToParent(item.children, parentKey),
                        };
                    }
                    return item;
                });
            };

            // 更新数据源和菜单数据
            const updatedData = values.parent
                ? addRecordToParent(dataSource, values.parent)
                : [...dataSource, newRecord];
            setDataSource(updatedData);
            setMenuData(updatedData);
        } else {
            // 编辑模式下，更新记录的标题等信息
            const recursiveUpdateTitle = (data, keyToUpdate) => {
                return data.map(item => {
                    if (item.key === keyToUpdate) {
                        return {
                            ...item,
                            title: values.name,
                            path: values.path,
                            icon: values.icon,
                            isShow: values.isShow,
                        };
                    }
                    if (item.children) {
                        return {
                            ...item,
                            children: recursiveUpdateTitle(item.children, keyToUpdate),
                        };
                    }
                    return item;
                });
            };

            // 更新数据源和菜单数据
            const updatedData = recursiveUpdateTitle(dataSource, selectedRecord.key);
            setDataSource(updatedData);
            setMenuData(updatedData);
        }
        setIsModalVisible(false); // 关闭模态框
    };

    // 处理开关显示状态切换
    const handleToggleShow = (checked, record) => {
        // 递归更新菜单项及其所有子菜单的显示状态
        const recursiveUpdateShow = (data, keyToUpdate, isChecked) => {
            return data.map(item => {
                if (item.key === keyToUpdate) {
                    const updatedItem = { ...item, isShow: isChecked }; // 更新当前菜单项的显示状态
                    if (item.children) {
                        updatedItem.children = item.children.map(child => ({ ...child, isShow: isChecked })); // 更新子菜单的显示状态
                    }
                    return updatedItem;
                }

                // 如果当前项有子菜单，递归更新子菜单的显示状态
                if (item.children) {
                    const updatedSubMenu = recursiveUpdateShow(item.children, keyToUpdate, isChecked);

                    // 检查子菜单的状态
                    const allChildrenUnchecked = updatedSubMenu.every(child => !child.isShow);

                    // 更新当前菜单项的显示状态，如果任何子菜单被打开，父菜单也要打开
                    let updatedItem = { ...item, children: updatedSubMenu };
                    if (isChecked) {
                        updatedItem.isShow = true;
                    } else if (allChildrenUnchecked) {
                        updatedItem.isShow = false;
                    }
                    return updatedItem;
                }
                return item; // 返回原始项
            });
        };

        // 使用递归函数更新数据源和菜单数据
        const updatedData = recursiveUpdateShow(dataSource, record.key, checked);
        setDataSource(updatedData);
        setMenuData(updatedData);
    };

    // 获取所有父菜单项的 key 和 title，用于选择父菜单项
    const getAllParentKeys = (data) => {
        let keys = [];
        const recursiveGetKeys = (items) => {
            items.forEach(item => {
                keys.push({ key: item.key, title: item.title });
                if (item.subMenu) {
                    recursiveGetKeys(item.subMenu);
                }
            });
        };
        recursiveGetKeys(data);
        return keys;
    };

    // 表格列配置
    const columns = [
        {
            title: '名称',
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: '图标',
            dataIndex: 'icon',
            key: 'icon',
            render: (icon) => icon && IconMap[icon], // 渲染图标
        },
        {
            title: '前端路径',
            dataIndex: 'path',
            key: 'path',
        },
        {
            title: '是否显示',
            dataIndex: 'isShow',
            key: 'isShow',
            render: (isShow, record) => ( // 渲染开关组件
                <Switch
                    checked={isShow}
                    onChange={(checked) => handleToggleShow(checked, record)}
                />
            ),
        },
        {
            title: '操作',
            key: 'actions',
            render: (text, record) => ( // 渲染操作按钮
                <Space size="middle">
                    <Button type="primary" onClick={() => handleEdit(record)}>编辑</Button>
                    <Button type="danger" onClick={() => handleDelete(record)}>删除</Button>
                </Space>
            ),
        },
    ];

    return (
        <>
            {/* 新增按钮容器 */}
            <div className="addButtonContainer">
                <PlusOutlined className="addIcon" />
                <span className="addText">数据展示</span>
                <Button type="primary" className="addButton" onClick={handleAdd}>
                    新增
                </Button>
            </div>

            {/* 表格组件 */}
            <Table
                columns={columns}
                dataSource={generateTableData(dataSource)}
                pagination={false}
                expandable={{
                    expandedRowKeys: expandedKeys,
                    onExpand: handleExpand,
                    rowExpandable: record => record.hasChildren, // 只有当菜单项有子菜单时才允许展开
                }}
            />

            {/* 编辑/新增记录的模态框 */}
            <Modal
                title={isAddMode ? "新增记录" : "编辑记录"}
                open={isModalVisible} // 更新为 visible
                onOk={handleOk}
                onCancel={handleCancel}
                footer={null}
            >
                <Form onFinish={onFinish} initialValues={selectedRecord ? { name: selectedRecord.title, path: selectedRecord.path, icon: selectedRecord.icon, isShow: selectedRecord.isShow, parent: selectedRecord.parentKey } : { name: '', path: '', icon: null, isShow: true, parent: null }}>
                    <Item name="name" label="名称" rules={[{ required: true, message: '请输入名称' }]}>
                        <Input />
                    </Item>
                    <Item name="path" label="前端路径" rules={[{ required: true, message: '请输入前端路径' }]}>
                        <Input />
                    </Item>
                    <Item name="icon" label="图标">
                        <Select allowClear>
                            {Object.keys(IconMap).map(key => (
                                <Option key={key} value={key}>{key}</Option>
                            ))}
                        </Select>
                    </Item>
                    <Item name="isShow" label="是否显示" valuePropName="checked">
                        <Switch />
                    </Item>
                    {/* 如果是新增模式，则显示父菜单项选择器 */}
                    {isAddMode && (
                        <Item name="parent" label="父菜单项">
                            <Select allowClear>
                                {/* 渲染所有父菜单项 */}
                                {getAllParentKeys(dataSource).map(item => (
                                    <Option key={item.key} value={item.key}>{item.title}</Option>
                                ))}
                            </Select>
                        </Item>
                    )}
                    <Item>
                        {/* 提交按钮 */}
                        <Button type="primary" htmlType="submit">
                            {isAddMode ? '新增' : '保存'}
                        </Button>
                    </Item>
                </Form>
            </Modal>
        </>
    );
};

export default MenuTable;